﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LANmine
{
    public partial class CheckinForm : Form
    {
        private Language lmLang;
        private Database rwDb = new Database("rw");
        String Qstr;

        public CheckinForm()
        {
            InitializeComponent();
        }

        public CheckinForm(Language lmLang)
            : this()
        {
            // Save the language object
            this.lmLang = lmLang;

            // Dock the window
            this.Dock = DockStyle.Fill;

            // Apply language
            ApplyLanguage();
        }

        #region Language Specifications
        /**
         * MainForm::ApplyLanguage()
         * ---------------------------
         * Overwrite all text properties of all elements in all forms with the right ones.
         */
        private void ApplyLanguage()
        {
            /**
             * Header label
             */
            this.lblCheckin.Text = this.lmLang.GetString("menu.btnCheckin");
            /* other labels & controls */
            this.txtSearchUser.Text = this.lmLang.GetString("checkin.txtSearch");
            this.btnCheckinUser.Text = this.lmLang.GetString("checkin.btnCheckin");

        }
        #endregion

        #region Member Functions

        /// <summary>
        /// Search the users table for a given string.
        /// </summary>
        /// <param name="Qstr">The string to search for</param>
        private void SearchUsers(String Qstr)
        {
            this.Qstr = Qstr;

            // Define database objects
            DataSet ds = new DataSet();
            DataTable dt;
            SqlConnection dbConn = this.rwDb.getDbConn();
            SqlDataAdapter da;

            try
            {
                da = new SqlDataAdapter("lmSearchUser", dbConn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                // Add Parameters
                da.SelectCommand.Parameters.Add("@Qstr", SqlDbType.VarChar, 255);
                da.SelectCommand.Parameters["@Qstr"].Value = Qstr;

                // Fill the DataSet from the DataAdapter
                da.Fill(ds, "users");

                // Extract the teams table from the dataset
                dt = ds.Tables["users"];

                // Check for empty result set
                if (dt.Rows.Count > 0)
                {
                    // Loop through a list of users
                    foreach (DataRow r in dt.Rows)
                    {
                        // Add the current record to the ListBox
                        lbxUsersFound.Items.Add(new ItemData(r["id"].ToString(), (r["naam"].ToString() + r["voornaam"].ToString() + " - " + r["email"].ToString())));
                    }

                    // Select the first entry
                    lbxUsersFound.SelectedIndex = 0;
                    // Enable button
                    btnCheckinUser.Enabled = true;
                }
                else
                {
                    // Add empty record
                    lbxUsersFound.Items.Add(lmLang.GetString("checkin.errNoUsers"));
                    // Disable button, no results
                    btnCheckinUser.Enabled = false;
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(lmLang.GetString("checkin.msgError") + "\n" + ex.Message);
            }
        }

        /// <summary>
        /// Check in a user
        /// The seats plan will indicate a seat to be placed
        /// </summary>
        /// <param name="userId"></param>
        private void CheckinUser(UInt32 userId)
        {
            try
            {
                Database dbUsers = new Database("rw");
                SqlConnection dbConn = dbUsers.getDbConn();
                DataSet dsUsers = new DataSet();
                DataTable dtUsers = new DataTable("deelnemers");

                // Create data adapters and command builders
                SqlDataAdapter daUsers = new SqlDataAdapter("SELECT TOP 1 * FROM deelnemers WHERE deelnemers.id='" + userId.ToString() + "'", dbConn);
                SqlCommandBuilder cbUsers = new SqlCommandBuilder(daUsers);

                // Fill the datatable
                daUsers.Fill(dtUsers);
                dsUsers.Tables.Add(dtUsers);

                // Modify DataSet
                dsUsers.Tables["deelnemers"].Rows[0]["checkedin"] = true;

                // Update the record
                daUsers.Update(dsUsers, "deelnemers");

                // Show messagebox the update succeeded
                MessageBox.Show(lmLang.GetString("checkin.msgCheckinSucceeded"));

                // Clear the search field
                txtSearchUser.Clear();
            }

            catch (Exception ex)
            {
                MessageBox.Show(lmLang.GetString("checkin.msgError") + "\n" + ex.Message);
            }
        }

        #endregion

        #region Event Handlers

        private void txtSearchUser_TextChanged(object sender, EventArgs e)
        {
            // Clear the ListBox
            lbxUsersFound.Items.Clear();

            // Check if the search box is empty
            if (txtSearchUser.Text.Length > 0)
            {
                // Search the database
                SearchUsers(txtSearchUser.Text);
            }
            else
            {
                // Add empty record
                lbxUsersFound.Items.Add(lmLang.GetString("checkin.errNoUsers"));
                // Disable checkin button
                btnCheckinUser.Enabled = false;
            }
        }

        private void btnCheckinUser_Click(object sender, EventArgs e)
        {
            /* user id uit de item data halen die we opvullen bij SearchUsers() */
            UInt32 userId = Convert.ToUInt32(((ItemData)lbxUsersFound.SelectedItem).itemdata);
            CheckinUser(userId);
        }

        #endregion 
    }
}
